﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using Sebarf.Core.Interfaces;
using Sebarf.Services.Interfaces;
using Sebastof.Serialisation;
using Sebastof.Services.Interfaces;
using Utils;

#endregion

namespace Sebastof.ProcessChains.ProcessSteps {
	/// <summary>
	/// This is another processing step (for single objects).
	/// If the an object with the attached metadata id was already loaded once, the previously loaded object will be returned.
	/// So loading the same object twice will return the identical (reference identical) objects.
	/// </summary>
	public class UseCachedObjectStep : ProcessStep<ObjectTransportContainer> {
		#region Public Properties

		[ServiceRequest]
		private ICachedDataRegistrationService CachedDataRegistrationService { get; set; }

		[ServiceRequest]
		private ICachedDataLocatorService CachedDataLocatorService { get; set; }

		[ServiceRequest]
		private IObjectSynchronisationService DatahandlerService { get; set; }

		#endregion

		#region Public Methods

		public UseCachedObjectStep(IServiceLocatorService locator) {
			CachedDataLocatorService = locator.GetRegisteredService<ICachedDataLocatorService>();
			CachedDataRegistrationService = locator.GetRegisteredService<ICachedDataRegistrationService>();
		}

		public UseCachedObjectStep() {
		}

		protected override ObjectTransportContainer OnProcess(ObjectTransportContainer toProcess) {
			if (toProcess.Value is ValueType || toProcess.Value is String || toProcess.Value == null) {
				return base.OnProcess(toProcess);
			}

			var key = toProcess.TransferedMetadata.GetMetadata<string>(toProcess.Value, "UniqueIdentifier");

			CachedDataLocatorService.RefreshObject(key, toProcess.TransferedData[key], toProcess.Value);

			toProcess.Value = DatahandlerService.MergeObject(key,
															  !CachedDataLocatorService.ContainsKey(key)
																? null
																: CachedDataLocatorService.GetCachedData<Object>(key),
															  toProcess.Value);
			//if (!CachedDataLocatorService.ContainsKey(key)) {
			//    CachedDataRegistrationService.AddOrUpdateCachedValue(key, toProcess.Value);
			//}
			//else {
			//    toProcess.Value = CachedDataLocatorService.GetCachedData<Object>(key);
			//}
			return base.OnProcess(toProcess);
		}

		#endregion
	}
}